<?php
namespace cubox;

class File{

    
    public static function realPath(string $path,string $basePath = ''){
        //如果是根目录
        if (substr($path,0,1)=='/'){
            return ROOT.$path;
        }

        //@@ 代表APP路径
        if (substr($path,0,2)=='@@'){
            return ROOT.DS.APP.substr($path,2);
        }

        //@根目录
        if (substr($path,0,1)=='@'){
            return ROOT.substr($path,1);
        }

        if ($basePath =='') $basePath = ROOT;
        if (substr($path,0,2)=='./'){
            $path = substr($path,2);
        }

        $path = str_replace(DS,'/',$path);
        $arr = explode('/',$path);
        $up_folder_number = 0;
        $up_lab  = true;
        $new_arr = array();

        foreach($arr as $v){
            if ($v=='..' && $up_lab){
                $up_folder_number ++;
            }else{
                $up_lab = false;
                $new_arr[] = $v;
            }
        }
        
        if ($up_folder_number>0){
            return dirname($basePath,$up_folder_number).DS.implode(DS,$new_arr);
        }else{
            return $basePath.DS.implode(DS,$new_arr);
        }

    }

    public static function cleanPath(string  $path){
        return str_replace('/',DS,preg_replace('/[\/\\\]+/','/',$path));
    }
    //公共  静态  函数  获取文件列表
    public static function fileList(string $path,string $ext = '',bool $childrenDir = false):array{
        
        $files = scandir($path);
        foreach($files as $k => $v){
            if ($v!='.' && $v!='..'){
                if (is_dir($path.DS.$v)){
                    if ($childrenDir){
                        $files[$k] = self::fileList($path.DS.$v,$ext,$childrenDir);
                    }else{
                        unset($files[$k]);
                    }
                }else{
                    if ($ext!='' && substr($v,-strlen($ext))!=$ext){
                        unset($files[$k]);
                    }
                }
            }
        }

        return $files;

    }

    public static function folderList(string $path):array{
        $re = [];
        $files = scandir($path);
        foreach($files as $k => $v){
            if ($v!='.' && $v!='..') continue;
            if (is_dir($path.DS.$v)) $re[] = $v;
        }

        return $re;
    }

    public static function copyFolder(string $src,string $dst){

        if (!is_dir($dst)) {
            if (!mkdir($dst, 0777, true)) {
                throw new \Exception('创建目录失败' .$dst);
            }
        }

        $dir = opendir($src);
        
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' )) {
                if ( is_dir($src . DS . $file) ) {
                    self::copyFolder($src . DS . $file,$dst . DS . $file);
                }
                else {
                    copy($src . DS . $file,$dst . DS . $file);
                }
            }
        }
        closedir($dir);
    }
    
}